﻿using System.IO;
using System.Text;
using System.Xml;

namespace FlightToolkit.SimProp
{
    internal static class XML
    {
        #region Internal
        internal static PropertySet Read(Symbols symbols, Stream inputStream)
        {
            XmlTextReader reader = new XmlTextReader(inputStream);

            NamespaceDef namespaceDef = null;

            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element: // The node is an element.
                        string[] names = reader.LocalName.Split('.');
                        string symbolName;
                        if (names.Length > 1)
                        {
                            // First look up the namespace
                            namespaceDef = symbols.GetNamespaceDef(names[0]);
                            symbolName = names[1];
                        }
                        else
                        {
                            // Use the current namespace
                            symbolName = names[0];
                        }

                        SymbolDef symDef = namespaceDef.GetSymbolDef(symbolName);

                        if (symDef.Type.Type == Type.PropertySet)
                        {
                            var documentSet = new PropertySet((PropertySetDef)symDef);
                            documentSet.ReadXML(symbols, reader);
                            return documentSet;
                        }
                        else
                        {
                            throw new InvalidDataException("Invalid symbol type");
                        }

                    case XmlNodeType.Text: //Display the text in each element.
                        break;

                    case XmlNodeType.EndElement: //Display the end of the element.
                        break;
                }
            }

            throw new InvalidDataException("Unexpected format");
        }

        internal static void Write(PropertySet documentSet, Stream stream)
        {
            XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);

            writer.Formatting = Formatting.Indented;
            writer.WriteStartDocument();

            documentSet.WriteXML(null, writer);

            writer.WriteEndDocument();
            writer.Flush();
        }
        #endregion
    }
}
